package com.ithero.usercenter.service.user;

import com.ithero.usercenter.dao.bonus.BonusEventLogMapper;
import com.ithero.usercenter.dao.user.UserMapper;
import com.ithero.usercenter.domain.dto.user.UserLoginDTO;
import com.ithero.usercenter.domain.entity.bonus.BonusEventLog;
import com.ithero.usercenter.domain.entity.user.User;
import com.ithero.usercenter.domain.dto.messaging.UserAddBonusMsgDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BonusEventLogMapper bonusEventLogMapper;

    public User findById(Integer id) {
        return this.userMapper.selectByPrimaryKey(id);
    }

    /**
     * 增加积分
     */
    @Transactional(rollbackFor = Exception.class)
    public void addBonus(UserAddBonusMsgDTO messageDTO) {
        // 当收到消息的时候执行的业务
        // 1. 为用户加积分
        Integer userId = messageDTO.getUserId();
        Integer bonus = messageDTO.getBonus();
        User user = userMapper.selectByPrimaryKey(userId);
        user.setBonus(user.getBonus() + bonus);
        userMapper.updateByPrimaryKeySelective(user);

        // 2. 记录日志到bonus_event_log表里面
        bonusEventLogMapper.insert(BonusEventLog.builder()
                .userId(userId)
                .value(bonus)
                .event("CONTRIBUTE")
                .createTime(new Date())
                .description(messageDTO.getDescription())
                .event(messageDTO.getEvent())
                .build());

        log.info("积分添加完毕...");
    }

    /**
     * 用户登录
     */
    public User login(UserLoginDTO loginDTO, String openId) {
        User user = this.userMapper.selectOne(
                User.builder()
                        .wxId(openId)
                        .build()
        );

        // 用户未注册，注册
        if (user == null) {
            User userToSave = User.builder()
                    .wxId(openId)
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickName())
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .roles("user")
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();

            this.userMapper.insertSelective(userToSave);
            return userToSave;
        }
        // 用户已注册，直接返回
        return user;
    }
}
